var ajax = require('../../utils/ajax.js');
var wxUtil = require('../../utils/wxUtil.js');
var util = require('../../utils/util.js');
var shopInfo = require('../../components/shopInfo/index.js');
var app = getApp();

Page({
  data: {
    dataLoaded: false,
    orderId: '',
    shop: {},
    order: {},
    totalPrice: '',
  },

  onLoad: function (options) {
    this.setData({
      orderId: options.orderId
    });
    this._initPage();
  },

  _initPage: function () {
    var _self = this;

    ajax.P(
      '/openapi/CHome/orderDetail',
      {
        orderId: this.data.orderId,
      },
      function (data) {
        var order = data.result.order
        var totalPrice = 0;

        order.goodsList.forEach(function (item) {
          totalPrice += parseFloat(item.price);
        });

        shopInfo.init('shopInfoData', _self);
        _self.setData({
          dataLoaded: true,
          order: order,
          shop: app.getShop(),
          totalPrice: totalPrice.toFixed(2),
        });
      });
  },

  /**
   * 未支付订单支付
   */
  _payOrder: function () {
    ajax.P(
      '/openapi/CHome/doPayAgain',
      {
        orderId: this.data.orderId,
        openId: app.getOpenId(),
      },
      function (data) {
        var wxPayParams = JSON.parse(data.result.wxPayParams);

        wxPayParams.success = function () {
          wx.redirectTo({ url: '../orderList/orderList?ty=1' });
        }
        wxUtil.wxPay(wxPayParams);
      });
  },

  /**
   * 申请退款
   */
  _applyRefund: function () {
    var self = this;

    ajax.P(
      '/openapi/CHome/applyOrderRefund',
      {
        orderId: this.data.orderId,
      },
      function (data) {
        util.alert('您已申请退款，请耐心等待商家处理', function () {
          wx.redirectTo({ url: '/pages/orderDetail/orderDetail?orderId=' + self.data.orderId });
        });
      });
  },
});